package models

import (
	"errors"
	"gorm.io/gorm"
	"my_gin_blog/dao"
	"my_gin_blog/utils/errmsg"
)

type Category struct {
	ID   uint   `gorm:"primary_key;auto_increment" json:"id"`
	Name string `gorm:"type:varchar(20);not null" json:"name"`
}

func GetCateList(pageSize, pageNum int) ([]Category, int64) {
	var cateList []Category
	var total int64
	err := dao.Db.Find(&cateList).Limit(pageSize).Offset((pageNum - 1) * pageSize).Error
	dao.Db.Model(&cateList).Count(&total)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, 0
	}
	return cateList, total
	//return nil, 0
}

// GetCateInfo 单个信息获取
func GetCateInfo(id int) (Category, int) {
	var cate Category
	dao.Db.Where("id=?", id).First(&cate)
	return cate, errmsg.SUCCESS
}

// CheckCategory 查询分类是否存在
func CheckCategory(name string) (code int) {
	var cate Category
	dao.Db.Select("id").Where("name = ?", name).First(&cate)
	if cate.ID > 0 {
		return errmsg.ERROR_CATENAME_USED //2001
	}
	return errmsg.SUCCESS
}

// CreateCate 新增分类
func CreateCate(data *Category) int {
	err := dao.Db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR // 500
	}
	return errmsg.SUCCESS
}

// EditCate 编辑分类信息
func EditCate(id int, data *Category) int {
	var cate Category
	var maps = make(map[string]interface{})
	maps["name"] = data.Name

	err := dao.Db.Model(&cate).Where("id = ? ", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// DeleteCate 删除分类
func DeleteCate(id int) int {
	var cate Category
	err := dao.Db.Where("id = ? ", id).Delete(&cate).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
